package com.cloudspace.jindun.rongyun;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.cloudspace.jindun.R;
import com.cloudspace.jindun.activity.CustomTitleBaseActivity;
import com.cloudspace.jindun.activity.RegisterActivity;
import com.cloudspace.jindun.activity.xiaoxi.HuatiZiliaoActivity;
import com.cloudspace.jindun.config.Configs;
import com.cloudspace.jindun.constants.Constants;
import com.cloudspace.jindun.ext.aq.AQUtility;
import com.cloudspace.jindun.log.APPLog;
import com.cloudspace.jindun.manager.MessageNumberManager;
import com.cloudspace.jindun.network.url.YXHttpUrl;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.AppPreferences;
import com.cloudspace.jindun.utils.VibratorUtils;
import com.cloudspace.jindun.websocket.WebSocketManager;
import com.cloudspace.jindun.websocket.WebSocketMessageController;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.ref.WeakReference;
import java.util.Locale;

import de.tavendo.autobahn.WebSocket;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationFragment;
import io.rong.imkit.widget.adapter.MessageListAdapter;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import okhttp3.Call;

public class ConversationActivity extends CustomTitleBaseActivity implements View.OnClickListener {
    private ImageView back;
    private TextView title;
    private ImageView titleright;
    private Conversation.ConversationType mConversationType;
    private String targetId;

    private boolean mInGroupChat = false;
    public static final int RQUEST_DETAIL =  100;

    private  ConversationFragment conversationFragment;
    private MessageListAdapter messageAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getIntent() == null || getIntent().getData() == null){
            RegisterActivity.showActivity(this);
            finish();
            return;
        }

        setContentView(R.layout.activity_conversation, false);
        initView();
        initData();
        setListener();

        mInGroupChat = AppPreferences.getBoolean(Constants.GROUPCHAT_ON, false);

        if (mInGroupChat){
            connectWebSocket(getWSUrl());
        }
    }

    private void initData() {
        targetId = getIntent().getData().getQueryParameter("targetId");

        mConversationType = Conversation.ConversationType.valueOf(getIntent().getData()
                .getLastPathSegment().toUpperCase(Locale.getDefault()));
        String titleName = getIntent().getData().getQueryParameter("title");
        if (!TextUtils.isEmpty(titleName)) {
            title.setText(titleName);
        }
        if (mConversationType.equals(Conversation.ConversationType.PRIVATE)) {
            titleright.setVisibility(View.GONE);
        }
    }

    private void setListener() {
        back.setOnClickListener(this);
        titleright.setOnClickListener(this);
        RongContext.getInstance().setConversationBehaviorListener(new RongIM.ConversationBehaviorListener() {
            @Override
            public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
                return false;
            }

            @Override
            public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
                return false;
            }

            @Override
            public boolean onMessageClick(Context context, View view, Message message) {

                return false;
            }

            @Override
            public boolean onMessageLinkClick(Context context, String s) {
                return false;
            }

            @Override
            public boolean onMessageLongClick(Context context, View view, Message message) {
                return false;
            }
        });
        RongIM.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
            @Override
            public boolean onReceived(Message message, int i) {
                APPLog.zxhLog(TAG + " onReceived:" + message + " sender id:" + message.getSenderUserId());
                MessageNumberManager.getInstance().addMessageUnread(message.getTargetId());

                if (UserSessionManager.isVibrateOn()) {
                    VibratorUtils.vibrate();
                }

                if (mConversationType.equals(Conversation.ConversationType.GROUP)) {
                    long sentTime = message.getSentTime();
                    requestData(YXHttpUrl.XX_UPTIME, targetId, sentTime);
                }

                return false;
            }
        });
        RongIM.getInstance().setSendMessageListener(new RongIM.OnSendMessageListener() {
            @Override
            public Message onSend(Message message) {
                return message;
            }

            @Override
            public boolean onSent(Message message, RongIM.SentMessageErrorCode sentMessageErrorCode) {
                if (mConversationType.equals(Conversation.ConversationType.GROUP)) {
                    long sentTime = message.getSentTime();
                    requestData(YXHttpUrl.XX_UPTIME, targetId, sentTime);
                }

                return false;
            }
        });
    }

    private void initView() {
        back = (ImageView) findViewById(R.id.xiaoxi_title_back);
        title = (TextView) findViewById(R.id.rl_text_title);
        titleright = (ImageView) findViewById(R.id.huati_image_title_r);

        conversationFragment = (ConversationFragment) getSupportFragmentManager().findFragmentById(R.id.conversation);
        messageAdapter = conversationFragment.getMessageAdapter();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.xiaoxi_title_back:
                finish();
                break;
            case R.id.huati_image_title_r:
                Intent intent = new Intent();
                if (!TextUtils.isEmpty(targetId)) {
                    intent.putExtra("qunID", targetId);
                }

                if (mInGroupChat) {
                    intent.putExtra("type", "2");
                } else {
                    intent.putExtra("type", "1");
                }

                intent.setClass(ConversationActivity.this, HuatiZiliaoActivity.class);
                startActivityForResult(intent, RQUEST_DETAIL);
                break;
        }
    }

    static class WebSocketLister implements WebSocketManager.IWebSocketListener {

        WeakReference<ConversationActivity> ref;

        public WebSocketLister(ConversationActivity fragment) {
            ref = new WeakReference<>(fragment);
        }

        boolean isFinish() {
            return ref == null || ref.get() == null ;

        }

        public void open() {
            APPLog.zxhLog(TAG + "ws open callback");
            ref.get().startPing();
        }

        public void error(int errorCode, String errorMessage) {
            APPLog.zxhLog("connect web socket errorCode : " + errorCode + " , errorMessage : " + errorMessage);
            if (errorCode == WebSocket.ConnectionHandler.CLOSE_NORMAL) {
                return;
            }
            // 关闭socket
            WebSocketMessageController.getInstance().close(true);
        }
    }

    private void startPing() {
        WebSocketMessageController.getInstance().startPing(15);
    }

    private WeakHandler webSocketHandler = new WeakHandler(this);
    private WebSocketLister mWsListener = new WebSocketLister(this);

    private String getWSUrl() {
        return String.format("ws://%s/channelId=%s/userId=%s", Configs.WS_IP, targetId,
                UserSessionManager.getInstance().getUserId());
    }

    public void connectWebSocket(final String ws) {
        APPLog.zxhLog(TAG + " connectWebSocket:" + ws);

        WebSocketMessageController.getInstance().setWSHandler(webSocketHandler);
        WebSocketMessageController.getInstance().setListener(mWsListener);

        WebSocketMessageController.getInstance().connect(ws);
    }

    static class WeakHandler extends WebSocketMessageController.WSHandler {
        private WeakReference<ConversationActivity> ref;

        public WeakHandler(ConversationActivity activity){
            ref = new WeakReference<ConversationActivity>(activity);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            if (ref == null || ref.get() == null){
                return;
            }

            APPLog.zxhLog(TAG + " handleMessage COMMAND_TYPE_NOTICE_READ");

            final ConversationActivity activity = ref.get();
            if (msg.what == COMMAND_TYPE_NOTICE_READ){
                if (activity.messageAdapter != null){
                    AQUtility.post(new Runnable() {
                        @Override
                        public void run() {
                            activity.messageAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }

        }
    }

    private void requestData(String url, String channelId, Long lastTime) {
        OkHttpUtils.post()
                .url(url)
                .addParams("channelId", channelId)
                .addParams("lastTime", lastTime + "")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {

                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RQUEST_DETAIL && resultCode == RESULT_OK){
            if (data != null &&
                    data.getBooleanExtra("delete", true)){
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}
